// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables
import 'package:flutter/material.dart';

import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:junyeyishu/widgets/QGNavigationBar.dart';
import '/utils/utils.dart';

class QGSaleCategoryPage extends StatefulWidget {
  const QGSaleCategoryPage({Key? key}) : super(key: key);
  @override
  State<QGSaleCategoryPage> createState() => _QGSaleCategoryPageState();
}

class _QGSaleCategoryPageState extends State<QGSaleCategoryPage> {
  int type = 0;

  dynamic data;
  List list = [];
  List otherList = [];

  @override
  void initState() {
    super.initState();

    onRefresh();
  }

  onRefresh() {
    Network.post(url_market_mySeriesList).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }

      var params = "series_ids=[${getIds(res.data)}]";
      Network.post(url_market_getMyAndOtherSeriesList, data: params)
          .then((res) {
        if (!res.success) {
          toast(res.msg);
          return;
        }

        data = res.data;

        list = data?["my"] ?? [];
        otherList = data?["other"] ?? [];
        if (mounted) setState(() {});
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
          children: [
            buildNav(),
            Container(color: Color(0xFFEAEAEA), height: 0.5.rpx),
            buildContent(),
          ],
        ));
  }

  buildNav() {
    return QGNavigationBar(
        title: "编辑藏品分类",
        rightItem: GestureDetector(
          onTap: onConfirm,
          child: Container(
            padding: EdgeInsets.all(10.rpx),
            child: Text(
              '确认',
              style: TextStyle(
                  color: Color(0xFF4AE3FF),
                  fontSize: 12.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ),
        ));
  }

  buildContent() {
    if (data == null) {
      return Expanded(
        child:
            Center(child: CircularProgressIndicator(color: Color(0xFFFFFFFF))),
      );
    }

    return 
    
    Expanded(
      child: ListView(
        padding: EdgeInsets.zero,
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 15.rpx),
            child: Column(children: [
              SizedBox(height: 20.rpx),
              buildMineTitle(),
              SizedBox(height: 20.rpx),
              buildAddList(),
              SizedBox(height: 25.rpx),
              buildOtherTitle(),
              SizedBox(height: 25.rpx),
              buildOtherList(),

              // Container(
              //   height: 80.rpx,
              //   color: Color(0XFF232A32),
              //   child: Container(
              //     height: 50.rpx,
              //     decoration: BoxDecoration(
              //       color: Color(0XFF4AE3FF),
              //       borderRadius: BorderRadius.circular(25)
              //     ),
              //     child:Text('确定',style: TextStyle(fontSize: 16,color: Color(0XFFFFFFFF))),
              //   ),
              // )
              
            ]),
          )
        ],
      ),
    );
  }

  buildMineTitle() {
    return Row(children: [
      Text(
        '我的分类',
        style: TextStyle(
            color: Color(0xFFFFFFFF),
            fontSize: 14.rpx,
            fontWeight: FontWeight.normal),
      ),
      Text(
        '（长按可拖动排序）',
        style: TextStyle(
            color: Color(0xFFFFFFFF),
            fontSize: 12.rpx,
            fontWeight: FontWeight.normal),
      ),
    ]);
  }

  buildTypeButtons() {
    var text_color = Color(0xFFFFFFFF);
    var select_text_color = Color.fromRGBO(255, 255, 255, 0.8);
    var bg_color = Color.fromRGBO(255, 255, 255, 1);
    var select_bg_color = Color(0xffE95412);

    return Row(
      children: [
        Expanded(
            child: GestureDetector(
          onTap: () {
            onSwitch(0);
          },
          child: Container(
            alignment: Alignment.center,
            height: 40.rpx,
            decoration: BoxDecoration(
              color: type == 0 ? select_bg_color : bg_color,
              borderRadius: BorderRadius.circular(10.rpx),
            ),
            child: Text(
              '我的分类',
              style: TextStyle(
                  color: type == 0 ? select_text_color : text_color,
                  fontSize: 14.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ),
        )),
        SizedBox(width: 10.rpx),
        Expanded(
            child: GestureDetector(
          onTap: () {
            onSwitch(1);
          },
          child: Container(
            alignment: Alignment.center,
            height: 40.rpx,
            decoration: BoxDecoration(
              color: type == 1 ? select_bg_color : bg_color,
              borderRadius: BorderRadius.circular(10.rpx),
            ),
            child: Text(
              '全部',
              style: TextStyle(
                  color: type == 1 ? select_text_color : text_color,
                  fontSize: 14.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ),
        )),
      ],
    );
  }

  buildAddList() {
    if (list.isEmpty) {
      return Center(
        child: Container(
          height: 44.rpx,
          alignment: Alignment.center,
          child: Text(
            '暂无数据',
            style: TextStyle(
                color: Color.fromRGBO(17, 17, 17, 0.6),
                fontSize: 12.rpx,
                fontWeight: FontWeight.normal),
          ),
        ),
      );
    }
    return GridView.builder(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 18,
          crossAxisSpacing: 8,
          childAspectRatio: 110 / 44.0,
        ),
        itemBuilder: (context, index) {
          return draggableItem(context, index, false);
        },
        itemCount: list.length);
  }

  var from = -1;
  var to = -1;

  Widget draggableItem(context, index, isOther) {
    return Stack(
      children: [
        Draggable(
          data: list[index],
          child: itemBuilder(context, index, isOther),
          feedback: itemBuilder(context, index, isOther),
          onDragCompleted: () {
            from = -1;
            to = -1;
            if (mounted) setState(() {});
          },
          onDragStarted: () {
            from = index;
          },
          onDragUpdate: (details) {},
        ),
        DragTarget(
          builder: (context, accepted, rejected) {
            if (to != index) {
              return Container();
            }

            if (from == to) {
              return Container();
            }
            return Container(
              height: 44.rpx,
              width: 110.rpx,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.red),
                borderRadius: BorderRadius.circular(10.rpx),
              ),
            );
          },
          onMove: (details) {
            to = index;
            if (mounted) setState(() {});
          },
          onLeave: (data) {
            to = -1;
            if (mounted) setState(() {});
          },
          onAccept: (itemData) {
            // 调整顺序
            var temp = list[from];
            list[from] = list[index];
            list[index] = temp;

            setState(() {});
          },
        )
      ],
    );
  }

  Widget itemBuilder(context, index, isOther) {
    return GestureDetector(
      onTap: () {
        onTap(index, isOther);
      },
      child: SizedBox(
        height: 44.rpx,
        width: 110.rpx,
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            Container(
              padding: EdgeInsets.all(5.rpx),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Color(0xFF232A32),
                borderRadius: BorderRadius.circular(26.rpx),
              ),
              child: FittedBox(
                child: Text(
                  isOther ? otherList[index]["name"] : list[index]["name"],
                  style: TextStyle(
                      color: Color(0xFFffffff),
                      fontSize: 12.rpx,
                      fontWeight: FontWeight.normal),
                ),
              ),
            ),
            Positioned(
              top: 4.rpx,
              right: 4.rpx,
              child: isOther
                  ? QGImage(asset: "sale_category_add", width: 14.rpx)
                  : QGImage(asset: "sale_category_sub", width: 14.rpx),
            ),
          ],
        ),
      ),
    );
  }

  buildOtherTitle() {
    return Row(children: [
      Text(
        '其它分类',
        style: TextStyle(
            color: Color(0xFFffffff),
            fontSize: 14.rpx,
            fontWeight: FontWeight.normal),
      )
    ]);
  }

  buildOtherList() {
    if (otherList.isEmpty) {
      return Center(
        child: SizedBox(
          height: 44.rpx,
          child: Text(
            '暂无数据',
            style: TextStyle(
                color: Color.fromRGBO(17, 17, 17, 0.6),
                fontSize: 12.rpx,
                fontWeight: FontWeight.normal),
          ),
        ),
      );
    }

    return GridView.builder(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 18,
          crossAxisSpacing: 8,
          childAspectRatio: 110 / 44.0,
        ),
        itemBuilder: (context, index) {
          return itemBuilder(context, index, true);
        },
        itemCount: otherList.length);
  }

  onSwitch(index) {
    // type = index;
    // var key = "my";
    // if (type == 1) {
    //   key = "all";
    // }

    // list = allData[key]?[0] ?? [];
    // otherList = allData[key]?[1] ?? [];

    setState(() {});
  }

  onTap(index, isOther) {
    if (isOther) {
      var temp = otherList[index];
      otherList.removeAt(index);
      list.add(temp);
    } else {
      var temp = list[index];
      list.removeAt(index);
      otherList.add(temp);
    }
    if (mounted) setState(() {});
  }

  getIds(data) {
    var ids = "";
    if (data is! List) return ids;

    for (var item in data) {
      if (item["id"] != "0") {
        ids += "${item["id"]},";
      }
    }

    if (ids.isNotEmpty) {
      ids = ids.substring(0, ids.length - 1);
    }

    return ids;
  }

  onConfirm() {
    var params = "series_ids=[${getIds(list)}]";
    Network.post(url_market_manageMySeries, data: params, context: context)
        .then((res) async {
      toast(res.msg);
      if (!res.success) {
        return;
      }
      eventBus.fire(EventRefreshTradeCategory());
    });
  }
}
